//
//  WebUrlViewController.m
//  Wallet
//
//  Created by noice on 2020/5/8.
//  Copyright © 2020 Wallet. All rights reserved.
//

#import "WebUrlViewController.h"
#import <WebKit/WebKit.h>

#import "MoodDiary-Swift.h"
#import <UMCommon/MobClick.h>

@interface WebUrlViewController () <WKNavigationDelegate, WKUIDelegate>

@property (weak, nonatomic) WKWebView *webView;

@property (strong, nonatomic) UIBarButtonItem *backItem;
@property (strong, nonatomic) UIBarButtonItem *lastItem;



@end

@implementation WebUrlViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc]init];
    configuration.allowsInlineMediaPlayback = YES;
    configuration.mediaTypesRequiringUserActionForPlayback = YES;
    WKWebView *webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, DEF_StatusBarAndNavigationBarHeight, DEF_SCREEN_WIDTH, DEF_SCREEN_HEIGHT - DEF_StatusBarAndNavigationBarHeight - DEF_Tabbar_SafeBottomMargin) configuration:configuration];
    
    webView.allowsBackForwardNavigationGestures = YES;
//    webView.configuration.allowsInlineMediaPlayback = YES;
//    webView.configuration.mediaTypesRequiringUserActionForPlayback = NO;
    webView.scrollView.bounces = NO;
    webView.scrollView.showsHorizontalScrollIndicator = NO;
    webView.scrollView.showsVerticalScrollIndicator = NO;
    
    NSString *appUrl = @"";

    switch (self.webUrlType) {
        case WebUrlTypeVideo:
            appUrl = @"https://pdotools.mmtravel.cn/moodiary/v/list.html";
            self.navigationItem.title = @"解压视频";
            break;
        case WebUrlTypeFeedback:
            appUrl = @"https://support.qq.com/product/291456";
            self.navigationItem.title = @"建议反馈";
            break;
        case WebUrlTypeAbout:
            appUrl = @"https://www.kancloud.cn/hellokiwi/moodiary/2021190";
            self.navigationItem.title = @"关于我们";
            break;
        case WebUrlTypeProtocol:
            appUrl = @"https://www.kancloud.cn/hellokiwi/user_agreement/1711703";
            self.navigationItem.title = @"用户协议";
            break;
        case WebUrlTypeStatement:
            appUrl = @"https://www.kancloud.cn/hellokiwi/user_agreement/1711704";
            self.navigationItem.title = @"隐私声明";
            break;
        case WebUrlTypePromotion:
            appUrl = self.webURL;
            self.navigationItem.title = self.webTitle;
            break;
        case WebUrlTypeYinsizhengce:
            appUrl = @"https://wordpress.m1book.com/yinsi-pgxqrj";
            self.navigationItem.title = @"隐私政策";
            break;
        case WebUrlTypeYonghuxieyi:
//            appUrl = @"https://www.apple.com.cn/legal/internet-services/itunes/cn/terms.html";
//            appUrl = @"https://www.apple.com/legal/internet-services/itunes/dev/stdeula/";
            appUrl = @"https://wordpress.m1book.com/用户协议-99";
            self.navigationItem.title = @"用户协议";
        default:
            
            break;
    }
    
    NSMutableURLRequest *request;
    
    switch (self.webUrlType) {
        case WebUrlTypeFeedback: {
            request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:[appUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]];
            [request setHTTPMethod:@"POST"];
            [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
        }
            break;
        default:
            request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:[appUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]];
            break;
    }
    
    [self.view addSubview:webView];
    
    webView.UIDelegate = self;
    webView.navigationDelegate = self;
    
    [webView loadRequest:request];
    
    self.webView = webView;
    
    self.backItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"关闭"] style:0 target:self action:@selector(backAction)];
    
    UIButton *lastBtn = [UIButton buttonWithType:0];
    [lastBtn setImage:[UIImage imageNamed:@"返回"] forState:0];
    [lastBtn addTarget:self action:@selector(lastAction) forControlEvents:UIControlEventTouchUpInside];
    [lastBtn sizeToFit];
    self.lastItem = [[UIBarButtonItem alloc] initWithCustomView:lastBtn];
    
    self.navigationItem.leftBarButtonItems = @[self.lastItem];
    
    
}

// 友盟页面统计
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [MobClick beginLogPageView:self.navigationItem.title];
    [MobClick event:@"pages_num" attributes:@{@"WangYe":[@"进入" stringByAppendingString:self.navigationItem.title]}];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [MobClick endLogPageView:self.navigationItem.title];
    [MobClick event:@"pages_num" attributes:@{@"WangYe":[@"离开" stringByAppendingString:self.navigationItem.title]}];
}

- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler
{
    NSURL *url = navigationAction.request.URL;
    NSString *urlString = (url) ? url.absoluteString : @"";
    // iTunes: App Store link
    //For example, wechat download link: https://itunes.apple.com/cn/app/id414478124? MT = 8
    if ([urlString containsString:@"//itunes.apple.com/"]) {
        [[UIApplication sharedApplication] openURL:url];
        decisionHandler(WKNavigationActionPolicyCancel);
        return;
    }
    else if ([urlString containsString:@"//apps.apple.com/"]) {
        [[UIApplication sharedApplication] openURL:url];
        decisionHandler(WKNavigationActionPolicyCancel);
        return;
    }
    
    // Protocol/URL-Scheme without http(s)
//    else if (url.scheme && ![url.scheme hasPrefix:@"http"]) {
//        [[UIApplication sharedApplication] openURL:url];
//        decisionHandler(WKNavigationActionPolicyCancel);
//        return;
//    }
//    else if (url.scheme && ![url.scheme hasPrefix:@"https"]) {
//        [[UIApplication sharedApplication] openURL:url];
//        decisionHandler(WKNavigationActionPolicyCancel);
//        return;
//    }
    decisionHandler(WKNavigationActionPolicyAllow);
}

- (void)webView:(WKWebView *)webView didFinishNavigation:(null_unspecified WKNavigation *)navigation {
    if ([self.webView canGoBack]) {
        self.navigationItem.leftBarButtonItems = @[self.lastItem, self.backItem];
    } else {
        self.navigationItem.leftBarButtonItems = @[self.lastItem];
    }
}

- (WKWebView *)webView:(WKWebView *)webView createWebViewWithConfiguration:(WKWebViewConfiguration *)configuration forNavigationAction:(WKNavigationAction *)navigationAction windowFeatures:(WKWindowFeatures *)windowFeatures {
    WKFrameInfo *frameInfo = navigationAction.targetFrame;
    if (![frameInfo isMainFrame]) {
        [webView loadRequest:navigationAction.request];
    }
    return nil;
}


- (void)backAction {
    if(self.webUrlType == WebUrlTypeYonghuxieyi || self.webUrlType == WebUrlTypeYinsizhengce){
        [self dismissViewControllerAnimated:YES completion:^{}];
    }else{
        [self.navigationController popViewControllerAnimated:YES];
    }
}

- (void)lastAction {
    
    if ([self.webView canGoBack]) {
        [self.webView goBack];
    } else {
        if(self.webUrlType == WebUrlTypeYonghuxieyi || self.webUrlType == WebUrlTypeYinsizhengce){
            [self dismissViewControllerAnimated:YES completion:^{}];
        }else{
            [self.navigationController popViewControllerAnimated:YES];
        }
    }
    
}

@end
